const db = require("../../dbutil/index");
const sql = require("../../dbutil/sql");
const token = require("../../util/token");

module.exports = {
    // 获取该条新闻的评论
    getComments: (req, res) => {
        let { news_id } = req.query;
        db.query(sql.comments.getComments, [news_id], (err, results) => {
            if (err) {
                res.send({ code: 505, msg: "数据库操作失败" });
            } else {
                // console.log(results);
                res.send({ code: 200, msg: "成功查询新闻评论", data:  results});
            }
        })
    },

    // 进行评论
    addComments: (req, res) => {
        let { uid, news_id, contents } = req.body;
        db.query(sql.comments.addComments, [uid, news_id, contents, Date.now()], (err, results) => {
            if (!uid || !news_id || !contents) {
                return res.send({ code: 401, msg: "添加的数据错误" });
            } else {
                if (err) {
                    res.send({ code: 505, msg: "数据库执行错误" });
                } else {
                    res.send({ code: 200, msg: "增加评论成功", data: { results } });
                }
            }
        })
    },


    // 获取评论
    getSelfComments: (req, res) => {
        let { news_id, uid } = req.query;
        db.query(sql.comments.getselfComments, [news_id, uid], (err, results) => {
            if (err) {
                res.send({ code: 505, msg: "数据库操作失败" });
            } else {
                if (results.length > 0) {
                    res.send({ code: 200, msg: "获取成功", data: results });
                } else {
                    res.send({ code: 201, msg: "获取失败" });
                }
            }
        })
    },


    
    // 删除评论
    deleteComments: (req, res) => {
        let { comments_id, uid } = req.body;
        db.query(sql.comments.deleteComments, [comments_id, uid], (err, results) => {
            if (err) {
                res.send({ code: 505, msg: "数据库操作失败" });
            } else {
                 if(results.affectedRows>0){
                    res.send({code:200,msg:"删除成功"})
                 }else{
                    res.send({code:201,msg:"删除失败"})
                 }
            }
        })
    }
}